<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

const animationDuration = 6000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    title: {
      type: String,
      default: ""
    },
    yName: {
      type: String,
      default: ""
    },
    chartdata: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    // setTimeout(() => {
    //   console.log(this.chartdata);
    //   console.log(2);
    //   this.initChart(this.chartdata.xData, this.chartdata.yData);
    // }, 500)
    
    // this.$nextTick(() => {
    //   console.log(this.chartdata);
    //   console.log(3);
    //   this.initChart(this.chartdata.xData, this.chartdata.yData)
    // })
  },  
  watch: {
    chartdata: {//深度监听，可监听到对象、数组的变化
      handler(val, oldVal){
        this.chartdata = val;        
        this.initChart(this.chartdata.xData, this.chartdata.yData)
      },
      deep:true //true 深度监听
     }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(xData, yData) {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        title: { 
          text: this.title,
          left: 'center',
          textStyle:{
              //文字颜色
              color:'#000000',
              //字体风格,'normal','italic','oblique'
              fontStyle:'normal',
              //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
              fontWeight:'bold',
              //字体系列
              fontFamily:'sans-serif',
              //字体大小
      　　　　 fontSize:18
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 50,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: xData,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: this.yName,
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: yData,
          animationDuration
        }]
      })
    }
  }
}
</script>
